#!/bin/bash

## Base directory
TOPDIR=/opt/data/data
PRIVPROJDIR=$TOPDIR/source/PrivProj
PROJDIR=$TOPDIR/proj

ECHO="echo -e"

function log() {
    $ECHO "jkbuild: $*"
}

function dir_none_create() {
    cdir=$1
    if [ ! -d $cdir ]; then
        log "Create $dir"
        mkdir -p $dir
    fi
}

function dir_none_exit() {
    edir=$1
    if [ ! -d $edir ]; then
        log "Error $edir not exist, exit"
        exit
    fi
}

function file_none_exit() {
    efile=$1
    if [ ! -f $efile ]; then
        log "Error $efile not exist, exit"
        exit
    fi
}
## Ready directory
readydirs="$TOPDIR $PROJDIR"
for dir in $readydirs; do
    dir_none_create $dir
done

## Ready done, start to deal with provproj

log "Start to deal with PrivProj"

dir_none_exit $PRIVPROJDIR

nginx_version="1.11.5"
mongo_version="3.2.10"
go_version="1.7.1"
nginxfile="$PRIVPROJDIR/nginx-$nginx_version.tar.gz"
mongofile="$PRIVPROJDIR/mongodb-linux-x86_64-*-$mongo_version.tgz"
gofile="$PRIVPROJDIR/go$go_version.linux-amd64.tar.gz"

files="$nginxfile $mongofile $gofile"
for file in $files; do

    file_none_exit $file
done

function do_go() {
    file=$gofile
    dstdir=$TOPDIR/clearsoft
    if [ ! -d $dstdir/go ]; then
        log "Extract $gofile "
        mkdir -p $dstdir
        tar xf $file -C $dstdir
#        mv $dstdir/go-* $dstdir/go
        echo "export GOROOT=\"\$GOROOT:$dstdir/go\"" >> ~/.bashrc
        echo "export PATH=\"\$PATH:$dstdir/go/bin\"" >> ~/.bashrc
    fi
}

function do_mongo() {
    mongo=$mongofile
    dstdir=$TOPDIR/clearsoft
    if [ ! -d $dstdir/mongodb ]; then
         log "Extract $mongo"
         mkdir -p $dstdir
         tar xf $mongo -C $dstdir
         mv $dstdir/mongodb-* $dstdir/mongodb
         echo "export PATH=\"\$PATH:$dstdir/mongodb/bin\"" >> ~/.bashrc
    fi
}

function do_nginx() {
    nginx=$nginxfile
    dstdir=$TOPDIR/clearsoft
    if [ ! -d $dstdir/nginx ]; then
        log "Extracting $nginx"
        tar xf $nginx -C $dstdir
        ## need configure
        current=`pwd`
        cd $dstdir/nginx-*
        ./configure --prefix=$dstdir/nginx
        make && make install
        if [ $? -ne 0 ]; then
            log "Error compile nginx"
            exit
        fi
        cd $current
        echo "export PATH=\"\$PATH:$dstdir/nginx/sbin\"" >> ~/.bashrc
    fi
}

do_go
do_mongo
do_nginx

log "Everythin done."
